<template>
  <s-layout :tabbarshow="false" id="layout" navbar="normal" :title="Title" :autoBack="true" leftIconColor="#000000" :bgColor="'#ffffff'" :titleStyle="{  color:'#000000',fontSize:'32rpx' }">
    <view class="container" :style="{paddingTop:(safeAreaInsets?.top + 44) + 'px'}">
      
      <view class="tabs">
        <view class="flex_box" v-for="item of state.tabs_item" :key="item.value" @tap="switchTabs(item.value,item.name)">
          <view class="tabs_item">{{ item.name }}</view>
          <view class="border_switch" v-show="item.value == tabs_switch ? true : false"></view>
        </view>
      </view>

      <!-- 表单盒子 -->
      <view class="form_box area">
        <scroll-view scroll-y style="height: 67vh" :enable-back-to-top="true">
          <!-- 表单结构 -->
          <fui-form ref="formRole" top="0" :model="FormData" :show="false" :errorPosition="2" :errorAlign="'left'">
            <!-- 选择项目 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="选择部门：" prop="department_id">
              <fui-input 
                textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="project_title = ''" :clearable="false" type="text" disabled @tap="chooseProject" :disabledColor="'#F9FAFF'" placeholder="请选择部门" v-model="project_title" border="none"
              >
              </fui-input>
            </fui-form-item>

            <!-- 输入名称 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="输入名称：" prop="title">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.title = ''" :clearable="false" type="text" placeholder="请输入名称" v-model="FormData.title" border="none"></fui-input>
            </fui-form-item>

            <!-- 选择日期 单个 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" v-if="Title == '当日排班'" :asterisk="true" label="选择日期：" prop="date">
              <fui-input 
                textAlign="right" :borderBottom="false" :padding="[0]" :size="26" :clearable="false" type="daterange" disabled :disabledColor="'#F9FAFF'" @tap="show_single = true" placeholder="请选择日期" v-model="the_same_day_date" border="none">
              </fui-input>
            </fui-form-item>

            <!-- 选择日期 范围 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" v-if="Title == '长期排班'" :asterisk="true" label="选择日期：" prop="date">
              <fui-input 
                textAlign="right" :borderBottom="false" :padding="[0]" :size="26" :clearable="false" type="daterange" disabled :disabledColor="'#F9FAFF'" @tap="show_scope = true" placeholder="请选择日期" v-model="long_time_date" border="none">
              </fui-input>
            </fui-form-item>

            <!-- 开始时间 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="上班时间：" prop="start_time">
              <fui-input 
                textAlign="right" :borderBottom="false" :padding="[0]" :size="26" :clearable="false" type="text" disabled :disabledColor="'#F9FAFF'" @tap="start = true" placeholder="请选择上班时间" v-model="FormData.start_time" border="none">
              </fui-input>
            </fui-form-item>

            <!-- 结束时间 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="下班时间：" prop="end_time">
              <fui-input 
                textAlign="right" :borderBottom="false" :padding="[0]" :size="26" :clearable="false" type="text" disabled :disabledColor="'#F9FAFF'" @tap="end = true" placeholder="请选择下班时间" v-model="FormData.end_time" border="none">
              </fui-input>
            </fui-form-item>

            <!-- 工时 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="工时:" prop="man_hour">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.man_hour = ''" :clearable="false" type="digit" placeholder="请输入工时"  v-model="FormData.man_hour" border="none"></fui-input>
            </fui-form-item>

            <!-- 详细地址 -->
            <view class="form_images">
              <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="详细地址：" prop="address">
              </fui-form-item>
              <view class="upload_box">
                <u--textarea :clearable="false" type="textarea" :height="'50'" disabled :disabledColor="'#F9FAFF'" @tap="openMap" v-model="FormData.address" placeholder="请输入详细地址" ></u--textarea>
              </view>
            </view>

            <!-- 打卡范围 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="打卡范围：" prop="clock_range">
              <fui-input 
              textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.clock_range = ''" @tap="dialogClick" :clearable="false" type="text"  disabled :disabledColor="'#F9FAFF'" placeholder="请选择打卡范围" v-model="FormData.clock_range" border="none">
              </fui-input>
            </fui-form-item>

            <!-- 人数（男） -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="人数（男）:" prop="man_num">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.man_num = ''" :clearable="false" type="number" placeholder="请输入人数" v-model="FormData.man_num" border="none"></fui-input>
            </fui-form-item>

            <!-- 薪资（男） -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="薪资（男）:" prop="man_salary">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.man_salary = ''" :clearable="false" type="number" placeholder="请输入薪资" v-model="FormData.man_salary" border="none"></fui-input>
            </fui-form-item>

            <!-- 人数（女） -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="人数（女）:" prop="woman_num">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.woman_num = ''" :clearable="false" type="number" placeholder="请输入人数" v-model="FormData.woman_num" border="none"></fui-input>
            </fui-form-item>

            <!-- 薪资（女） -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="薪资（女）:" prop="woman_salary">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.woman_salary = ''" :clearable="false" type="number" placeholder="请输入薪资" v-model="FormData.woman_salary" border="none"></fui-input>
            </fui-form-item>

            <!-- 代理商工资（男） -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="代理商工资（男）:" prop="agent_man_salary">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.agent_man_salary = ''" :clearable="false" type="number" placeholder="请输入代理商工资(男)" v-model="FormData.agent_man_salary" border="none"></fui-input>
            </fui-form-item>

            <!-- 代理商工资（女） -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="代理商工资（女）:" prop="agent_woman_salary">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.agent_woman_salary = ''" :clearable="false" type="number" placeholder="请输入代理商工资(女)" v-model="FormData.agent_woman_salary" border="none"></fui-input>
            </fui-form-item>

            <!-- 联系方式 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="联系方式：" prop="contact_tel">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.contact_tel = ''" :clearable="false" type="number" placeholder="请输入联系方式" v-model="FormData.contact_tel" border="none"></fui-input>
            </fui-form-item>

            <!-- 称呼 -->
            <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="联系人：" prop="contact_name">
              <fui-input textAlign="right" :borderBottom="false" :padding="[0]" :size="26" @clear="FormData.contact_name = ''" :clearable="false"  placeholder="请输入联系人" v-model="FormData.contact_name" border="none"></fui-input>
            </fui-form-item>

            <!-- 用工需求 -->
            <view class="form_images">
              <fui-form-item :labelWidth="180" :labelSize="26" :bottomBorder="false" :asterisk="true" label="用工需求:" prop="demand">
              </fui-form-item>
              <view class="upload_box">
                <editor id="editor" class="ql-container" placeholder-style="font-style: normal;" placeholder="请输入用工需求" @input="contentInput($event)" @statuschange="onStatusChange" style="background-color: #F9F9F9;"></editor>
              </view>
            </view>

          </fui-form>
        </scroll-view>
      </view>

    </view>
  </s-layout>

  <!-- 底部提交按钮 -->
  <view>
    <s-button @netWork="submitForm" :text="text"></s-button>
  </view>

      <!-- 底部弹出组件 && 部门弹出 -->
      <s-project-class @selectedData="switchTitle" @subcomponentSearch="subcomponentSearch" :arrayList="projectDataList" ref="popupListRef" :searchBoxIsShow="false"   :showGoLink="'#'"></s-project-class>
      
      <!-- 日期 范围 -->
      <!-- <up-calendar :closeOnClickOverlay="true" :show="show_scope" :mode="mode_scope" @confirm="confirm_scope" @close="close_scope"></up-calendar> -->
      <fui-date-picker :show="show_scope" range type="3" :value="time.minDate" :maxDate="time.maxDate" @change="confirm_scope" @cancel="close_scope"></fui-date-picker>
      <!-- 日期 单个 -->
      <!-- <up-calendar :closeOnClickOverlay="true" :show="show_single" :mode="mode_single" @confirm="confirm_single" @close="close_single"></up-calendar> -->
      <fui-date-picker :show="show_single" type="3" :value="time.minDate" :maxDate="time.maxDate" @change="confirm_single" @cancel="close_single"></fui-date-picker>
      
      <!-- 时间选择器 开始时间 -->
      <fui-date-picker :warning_show="true" range :show="start" type="6" :title="'选择开始时间'" @change="confirm_start" @cancel="cancel_start"></fui-date-picker>
      <!-- 时间选择器 结束时间 -->
      <fui-date-picker :warning_show="true" range :show="end" type="6" :title="'选择结束时间'" @change="confirm_end" @cancel="cancel_end"></fui-date-picker>
</template>

<script setup>
import sheep from '@/sheep';
import { ref, reactive, computed, watch } from 'vue';
import { onLoad, onShow,onUnload } from '@dcloudio/uni-app';
import { baseUrl } from "@/sheep/config";
const { safeAreaInsets } = uni.getSystemInfoSync();
// 用户信息
const userInfo = sheep.$store('user').userInfo;
// 页面销毁的时候将监听事件清掉 
onUnload(() => {
  // uni.$off('getAddress'); // 清除名为'getAddress'的事件监听器
})
  const time = reactive({
    minDate:'',
    maxDate:'',
    monthNum:'13',
    intraday:[]
  })

  // 设置默认日期，最大值为今天，最小值为去年今天
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  if (month <= 9) {
      month = '0' + month;
  }
  if (day <= 9) {
      day = '0' + day;
  }
  let minyear = year - 1;
  time.minDate = year + '-' + month + '-' + day;
  time.maxDate = (year + 1) + '-01-01';
  time.intraday = [year + '-' + month + '-' + day]


const text = ref("提交");
const Title = ref('');
const state = reactive({
titleStyle:{
  color:'#ffffff',
  fontWeight:700
},
bgColor:'rgba(0,0,0,0)',
tabs_item:[
  {name:'当日排班',value:0},
  {name:'长期排班',value:1}
]
})
// 用工需求
const contentInput = (e) => {
  FormData.value.demand = e.detail.html
}

// 禁止用户输入打卡范围
const dialogClick = () => {
if(!FormData.value.address) {
  uni.showToast({
    title:'请先输入详细地址',
    icon:'none'
  })
}
}


// 日期选择

// 范围
const mode_scope = ref('range')
const show_scope = ref(false)
const long_time_date = ref('')
const the_same_day_date = ref('')
const confirm_scope = (e) => {
  long_time_date.value = `${e.startDate.result} - ${e.endDate.result}`
  FormData.value.date = [e.startDate.result,e.endDate.result]

  close_scope()
}
const close_scope = () => {
  show_scope.value = false
}

// 单个
const mode_single = ref('single')
const show_single = ref(false)

const confirm_single = (e) => {
  the_same_day_date.value = e.result
  FormData.value.date = e.result
  close_single()
}
const close_single = () =>   {
  show_single.value = false
}

// 时间选择
// 开始时间 
const start = ref(false)
const close_start = () => {
  start.value = false
}
const confirm_start = (e) => {
 
  FormData.value.start_time = `${e.startDate.result}-${e.endDate.result}`
  close_start()
}
const cancel_start = () => {
  close_start()
}

// 结束时间 
const end = ref(false)
const close_end = () => {
  end.value = false
}
const confirm_end = (e) => {
  FormData.value.end_time = `${e.startDate.result}-${e.endDate.result}`
  close_end()
}
const cancel_end = () => {
  close_end()
}

const labelStyle = ref({
color:'$uni-text-color',
fontWeight:500,
fontSize:'26rpx'
})

// tabs 切换
const tabs_switch = ref()
const switchTabs = (value,title) => {
  tabs_switch.value = value
  Title.value = title
  project_title.value = ''
  long_time_date.value = ''
  the_same_day_date.value = ''
  FormData.value = {
    department_id: '', // 项目ID
    man_hour:'',//工时
    title: '', // 名称
    start_time: '', // 开始时间
    end_time: '', // 结束时间
    date: '', // 日期
    lon: '', // 经度
    lat: '', // 纬度
    address: '', // 详细地址
    clock_range: '', // 打卡范围
    man_num: '', // 人数（男）
    man_salary: '', // 薪资（男）
    woman_num: '', // 人数（女）
    woman_salary: '', // 薪资（女）
    agent_man_salary:'', // 代理商工资 男
    agent_woman_salary:'', // 代理商工资 女
    demand:'',//用工需求
    contact_tel:userInfo.mobile, //联系方式
    contact_name:userInfo.nickname //联系人
  }
}

onLoad((options) => {
let params={
  is_all:'0',
  is_include_main:'0'
}
projectList(params);
Title.value = options.title;
tabs_switch.value = options.tabs
// 获取经纬度 && 详细地址
uni.$on('getAddress',(e) => {
  FormData.value.clock_range = e.scope // 打卡范围
  FormData.value.address = e.Address  // 详细地址
  FormData.value.lon = e.Lat    // 经度
  FormData.value.lat = e.Lon    // 纬度
})
});
// 表单数据
const FormData = ref({
department_id: '', // 项目ID
title: '', // 名称
man_hour:'',//工时
start_time: '', // 开始时间
end_time: '', // 结束时间
date: '', // 日期
lon: '', // 精度
lat: '', // 纬度
address: '', // 详细地址
clock_range: '', // 打卡范围
man_num: '', // 人数（男）
man_salary: '', // 薪资（男）
woman_num: '', // 人数（女）
woman_salary: '', // 薪资（女）
agent_man_salary:'', // 代理商工资 男
agent_woman_salary:'', // 代理商工资 女
demand:'',//用工需求
contact_tel:userInfo.mobile, //联系方式
contact_name:userInfo.nickname //联系人
});

// 表单验证
const rules = [
  {
    name: "department_id",
    rule: ["required"],
    msg: ["请选择部门"]
  },
  {
    name: "title",
    rule: ["required"],
    msg: ["请输入名称"]
  },
  {
    name: "date",
    rule: ["required"],
    msg: ["请选择日期"],
  },
  {
    name: "start_time",
    rule: ["required"],
    msg: ["请选择开始时间"]
  },
  {
    name: "end_time",
    rule: ["required"],
    msg: ["请选择结束时间"]
  },
  {
    name: "man_hour",
    rule: ["required"],
    msg: ["请输入工时"]
  },
  {
    name: "address",
    rule: ["required"],
    msg: ["请输入详细地址"]
  },
  {
    name: "clock_range",
    rule: ["required"],
    msg: ["请选择打卡范围"]
  },
  {
    name: "man_num",
    rule: ["required"],
    msg: ["请输入员工（男）的人数"],
    validator:[{
      msg:'人数必须是正整数',
      method:function(rule, value, callback) {
        if(Number.isInteger(rule)) {
          return true
        }
      }
    }]
  },
  {
    name: "man_salary",
    rule: ["required"],
    msg: ["请输入员工（男）的薪资"]
  },
  {
    name: "woman_num",
    rule: ["required"],
    msg: ["请输入员工（女）的人数"],
    validator:[{
      msg:'人数必须是正整数',
      method:function(rule, value, callback) {
        if(Number.isInteger(rule)) {
          return true
        }
      }
    }]
  },
  {
    name: "woman_salary",
    rule: ["required"],
    msg: ["请输入员工（女）的薪资"]
  },
  {
    name: "agent_man_salary",
    rule: ["required"],
    msg: ["请输入代理商(男)薪资"]
  },
  {
    name: "agent_woman_salary",
    rule: ["required"],
    msg: ["请输入代理商(女)薪资"]
  },
  {
    name: "contact_tel",
    rule: ["required","isMobile"],
    msg: ["请输入联系方式","手机号码不正确"]
  },
  {
    name: "contact_name",
    rule: ["required"],
    msg: ["请输入联系人姓名"]
  },
  {
    name: "demand",
    rule: ["required"],
    msg: ["请输入用工需求"]
  }
];

const formRole = ref();  
const submitForm = () => {
  uni.$u.throttle(() => {
    formRole.value.validator(FormData.value, rules,true).then(async res => {
      if(res.isPassed) {
        const resust = await sheep.$api.project.scheduleAdd(FormData.value);
        if(resust.code == 1) {
          sheep.$helper.toast(resust.msg);
          // #ifdef MP
          sheep.$platform.useProvider('wechat').subscribeMessage('task_apply_notice');
          // #endif
          setTimeout(() => {
            sheep.$router.back(true);
          },1000)
        } else {
          sheep.$helper.toast(resust.msg);
        }
      } else {
        sheep.$helper.toast('请仔细核对内容！');
      }
    }).catch((err) => {
      console.log(err);
    });
  }, 500)
// if(Title.value == '当日排班') {
//   FormData.value.date = FormData.value.date.join(',')
// }
};

//项目选择 // 切换项目------------------------
const chooseProject = () => {
popupListRef.value.open()
}
const popupListRef = ref()
// 调用接口：获取项目列表
const projectDataList = ref([])
const projectList = async (params = null) => {
const res = await sheep.$api.app.getDepartment(params);
projectDataList.value = res.data;
};


// 项目id
const department_id = ref()
const project_title  =  ref()
// 子组件触发的方法将项目title改变
const switchTitle = (data) => {
project_title.value = data.jointTitles
FormData.value.department_id = data.id
}


// 构造查询字符串
const queryString = `?address=${FormData.value.address}`;
// 点击选择详细地址
const openMap = () => {
uni.navigateTo({
  url:`./map?${queryString}`
});
};


</script>

<!-- 第一个 style 标签 -->
<style scoped lang="scss">
page {
  width: 100%;
  height: 100%;
}

// 版心
.area {
  width: calc(100% - 40rpx);
  margin: 0 20rpx;
}



// 背景图片盒子
.container {
  background-size: cover; /* 或 contain */
  // tabs
  .tabs {
    background-color: #ffffff;
    height: 120rpx;
    display: flex;
    .flex_box {
      width: 50%;
      height: 100%;
      font-family: PingFangSC;
      color: #000000;
      font-weight: $uni-font-weight;
      font-size: $uni-font-size-base;
      font-style: normal;
      text-decoration: none;
      text-align: center;
      position: relative;
      .tabs_item {
        line-height: 120rpx;
      }
      .border_switch {
        width: 60rpx;
        height: 6rpx;
        border-radius: 2px;
        background: linear-gradient(90deg, rgba(0, 56, 247, 1) 0%, rgba(77, 139, 255, 1) 100%); 
        position: absolute;
        left: 0;
        right: 0;
        margin: auto;
        bottom: 30rpx;
      }
    }
  }

  // 表单盒子
  .form_box {
    width: calc(100% - 100rpx);
    margin-top: 20rpx;
    border-radius: 16rpx;
    background-color: #FFFFFF;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
    padding: 30rpx 30rpx;
    }
    :deep(.u-form-item){
      margin-bottom: 16rpx !important;
    }
    :deep(.u-form-item__body) {
      height: 80rpx;
      padding: 0 10rpx 0 30rpx;
      background-color: #F9F9F9;
      border-radius: 16rpx;
      .u-form-item__body__left{
        width: 216rpx !important;
      }
    }
    :deep(.u-form-item__body__right__content ){
      height: 80rpx !important;
    }
}

// 弹出框
.popup_box {
width: 100%;
height: 50%;
background-color: $uni-bg-color;
border-top-right-radius: 30rpx;
border-top-left-radius: 30rpx;
text-align: center;
font-weight: 700;
color: #333;
font-size: 30rpx;
.title {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
}
.name {
  width: 100%;
  height: 50vh;
  .list {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background-color: $uni-bg-color;
  }
  .list_loading {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    font-weight: 400;
    color: #666;
    background-color: $uni-bg-color;
  }
}
}
//现住址
.now_address{
:deep(.u-form-item__body ){
  .u-form-item__body__left__content__label{
    height: 80rpx !important;
    margin-top: -60rpx;
  }
  height: 180rpx !important;
}
:deep(.u-form-item__body__right){
  .u-form-item__body__right__content {
    height: 180rpx !important;
  }
    .input-placeholder{
      color: #606266 !important;
    }
  }
  :deep(.u-textarea){
    background-color: #F9F9F9 !important;
  }

}
:deep(.u-form-item__body__right__message ){
    text-align: right !important;
    margin-top: 10rpx;
  }
  // 用工需求
.remark {
  width: 100%;
 :deep(.u-form-item__body){
  height: auto !important;
  flex-direction: column !important; 
  .u-form-item__body__left__content{
    height: 90rpx !important;
  }
 }
}

// 用工需求
.form_images {
  .upload_box {
    margin-top: 15rpx;
    font-size: 26rpx;
    font-style: normal;
  }
} 

</style>

<!-- 第二个  style  标签 -->
<style lang="scss">
  #editor {
    font-style: normal;
    padding: 20rpx 20rpx 20rpx 20rpx;
  }

  .ql-editor.ql-blank:before {
    font-style: normal !important;
  }
</style>